const serialize = require("form-serialize")

/**
 * 目标1：信息渲染
 *  1.1 获取用户的数据
 *  1.2 回显数据到标签上
 * */
const creator = '播仔'
axios({
    url: 'http://hmajax.itheima.net/api/settings',
    params: {
        creator
    }
}).then(result => {
    const userObj = result.data.data
    //回显数据到标签上
    Object.keys(userObj).forEach(key => {
        if (key === 'avatar') {
            //赋予默认头像
            document.querySelector('.prew').src = userObj[key]
        } else if (key === 'gender') {
            const gRadioList = document.querySelectorAll('.gender')
            //0男1女
            const gNum = userObj[key]
            gRadioList[gNum].checked = true
        } else {
            //赋予默认内容
            document.querySelector(`${key}`).value = userObj[key]
        }
    })
})
//修改头像 
document.querySelector('.upload').addEventListener('change', e => {
    //获取头像文件
    console.log(e.target.files[0]);
    const fd = new FormData()
    fd.append('avatar', e.target.files[0])
    fd.append('creator', creator)
    //提交到服务器并更新头像
    axios({
        url: 'http://hmajax.itheima.net/api/avatar',
        method: 'PUT',
        data: fd
    }).then(result => {
        const imgUrl = result.data.data.avatar
        document.querySelector('.prew').src = imgUrl
    })
})
//提交表单
document.querySelector('.submit').addEventListener('click', e => {
    //收集表单信息
    const userForm = document.querySelector('.user-form')
    const userObj = serialize(userForm, { hash: true, empty: true })
    userObj.creator = creator
    //性别数字字符 转成数字类型
    userObj.gender = +userObj.gender
    console.log(userObj);
    //提交到服务器
    axios({
        url: 'http://hmajax.itheima.net/api/settings',
        method: 'PUT',
        data: userObj
    }).then(result => {
        //提示框
        //创建toast对象
        const toastDom = document.querySelector('.my-toast')
        const toast = new bootstrap.Toast(toastDom)
        //显示
        toast.show()
    })
})





